/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

/**
 * 一个简单的查询面板
 *
 * @author vacoor
 */
Ext.define('Nothing.ux.form.SearchPanel', {
    extend: 'Ext.form.Panel',
    alias: ['widget.searchpanel'],
    mixins: {
        bindable: 'Ext.util.Bindable'
    },

    store: null,

    searchText: '查询',
    resetText: '重置',
    // ------------
    layout: 'column',
    border: false,
    bodyPadding: 10,
    defaults: {
        width: 220,
        labelWidth: 80,
        xtype: 'textfield',
        margin: '10px 5px 0',
        labelAlign: 'right'
    },

    initComponent: function () {
        var me = this;

        me.buttons = [
            {
                text: me.searchText,
                //handler: Ext.Function.bind(me.doSearch, me)
                scope: me,
                handler: me.doSearch
            },
            {
                text: me.resetText,
                scope: me,
                handler: me.doReset
            }
        ];

        this.callParent(arguments);

        me.bindStore(me.store || 'ext-empty-store', true);
    },

    doReset: function (button, event) {
        var me = this;

        me.getForm().reset();
    },

    doSearch: function (button, event) {
        var me = this,
            filters = [],
            fields = me.getForm().getFields().items;

        button.setDisabled(true);

        Ext.each(fields, function (field) {
            // getSubmitValue (不是value, 提交时会转换eg:日期)
            var value = field.getSubmitValue();

            if (field.disable && Ext.isEmpty(value)) {
                return;
            }

            // 这里最好是转换为 Filter 对象, 否则 local 时无法过滤
            filters.push({
                property: field.name,
                operation: field.operation || 'EQ',
                fieldType: field.fieldType || 'S',
                value: value
            });
        });

        me.store.filters.clear();
        me.store.filters.addAll(filters);
        // 这里使用替换, 避免替换掉默认过滤, 不行, 这样条件会叠加...
        // store.replace(filters[0])

        me.store.loadPage(1, {
            callback: function () {
                button.setDisabled(false);
            }
        });
    }
});
